﻿using System;
using System.Collections.ObjectModel;
using Windows.UI.Xaml;

namespace Stopwatch.Data
{
    public class Stopwatch
    {
        private Clock _clock;
        private readonly ObservableCollection<Clock> _clocks;

        private readonly DispatcherTimer _timer = new DispatcherTimer();

        private uint _count;
        private DateTime _startTime;
        private DateTime _lastTime;
        private DateTime _nowTime;

        public Stopwatch()
        {

            _count = 1;
            _clock = new Data.Clock() { Count = _count, Span = TimeSpan.Zero, Period = TimeSpan.Zero };
            _clocks = new ObservableCollection<Clock>();
            _timer.Tick += new EventHandler<object>(OnTimerTick);
            this.IsStart = false;
        }

        private void OnTimerTick(object sender, object e)
        {
            _nowTime = DateTime.Now;
            _clock.Count = _count;
            _clock.Span = _nowTime - _startTime;
            _clock.Period = _nowTime - _lastTime;
        }

        public bool IsStart { get; set; }

        public Clock Clock { get { return _clock; } }

        public ObservableCollection<Clock> Clocks { get { return _clocks; } }

        public void Start()
        {
            _nowTime = DateTime.Now;
            _startTime = _lastTime = _nowTime;
            _clock.Count = _count;
            _clock.Period = _nowTime - _lastTime;
            _clock.Span = _nowTime - _startTime;

            if (!this.IsStart)
            {
                _timer.Start();
                this.IsStart = true;
            }
        }

        public void Pause()
        {
            if (_timer.IsEnabled)
            {
                _timer.Stop();
                this.IsStart = false;
            }
        }

        public void Append()
        {
            // 绑定的时候不能改变对象
            var clock = new Data.Clock() { Count = _count, Span = _clock.Span, Period = _clock.Period };
            _clocks.Add(clock);
            _count++;
            _nowTime = DateTime.Now;
            _lastTime = _nowTime;
            
        }
    }
}
